﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class Server :Singleton<Server>
{
    //string ip = "localhost";
    string ip = "127.0.0.1";
    //string ip = "192.168.105.24";
    int port = 8500;
    TcpListener listener;

    HanderCenter center = new HanderCenter();

    public void Init()
    {
        IPAddress adress = IPAddress.Parse(ip);
        listener = new TcpListener(adress, port);
        listener.Start();//开启服务器侦听
        Console.WriteLine("服务器开始监听");

        //开启异步接受client线程
        listener.BeginAcceptTcpClient(OnAcceptClient, null);
    }

    //异步接受客户端回调
    private void OnAcceptClient(IAsyncResult ar)
    {
        TcpClient client = listener.EndAcceptTcpClient(ar);
        Console.WriteLine("客户端连接：" + client.Client.RemoteEndPoint);

        //把客户端抛给一个类
        UserToken token = new UserToken(client);

        //再次开启异步接收线程
        listener.BeginAcceptTcpClient(OnAcceptClient, null);
    }

    //接受消息
    public void OnMessage(UserToken token,Protocol command, byte[] content)
    {
        center.OnReceive(token, command,content);
    }

    //断开连接
    public void Disconnect(UserToken token)
    {
        center.Disconnect(token);
    }



    #region 广播消息
    //发送消息
    public static void Send<T>(UserToken token, Protocol cmd, T t)
    {
        token.Send(cmd, Util.Serialize(t));
    }

    //广播给其他人
    public static void BroadOther(UserToken except, Protocol command, byte[] content)
    {
        for (int i = 0; i < UserManager.Instance.UserList.Count; i++)
        {
            UserToken token = UserManager.Instance.UserList[i];
            if (token != except)
            {
                token.Send(command, content);
            }
        }
    }
    public static void BroadOther<T>(UserToken except, Protocol command, T t)
    {
        for (int i = 0; i < UserManager.Instance.UserList.Count; i++)
        {
            UserToken token = UserManager.Instance.UserList[i];
            if (token != except)
            {
                Server.Send(token, command, t);
            }
        }
    }
    //广播所有人
    public static void BroadAll(Protocol command, byte[] content)
    {
        for (int i = 0; i < UserManager.Instance.UserList.Count; i++)
        {
            UserToken token = UserManager.Instance.UserList[i];

            token.Send(command, content);
        }
    }
    public static void BroadAll<T>(Protocol command, T t)
    {
        for (int i = 0; i < UserManager.Instance.UserList.Count; i++)
        {
            UserToken token = UserManager.Instance.UserList[i];

            Server.Send(token, command, t);
        }
    }
    #endregion

}
